<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\Common\Robot\Robot;
use App\CustHub\Amqp\Producers\ActiveAddFriendProducers;
use App\CustHub\Amqp\Producers\SendRecordProducers;
use App\CustHub\Constants\ContactTaskCenterTyperConstants;
use App\CustHub\Constants\OpSchemeTypeConstants;
use App\CustHub\Constants\RoomInviteLogTypeConstants;
use App\CustHub\Constants\SendConfigConstants;
use App\CustHub\Dto\ActiveAddFriendProducersDto;
use App\CustHub\Dto\ContactTcContentDto;
use App\CustHub\Dto\SendRecordProducersDto;
use App\CustHub\Helpers\TagReplacer;
use App\CustHub\Mapper\ActiveAddFriendMapper;
use App\CustHub\Mapper\ActiveAddFriendRobotMapper;
use App\CustHub\Mapper\ChContactMapper;
use App\CustHub\Mapper\ChOpSchemeRobotMapper;
use App\CustHub\Mapper\ChRobotMapper;
use App\CustHub\Mapper\ChRoomMapper;
use App\CustHub\Mapper\ChRoomMemberMapper;
use App\CustHub\Model\ChAddFriendContent;
use App\Robot\Dto\CommonJobDto;
use App\Robot\Job\CommonJob;
use App\Robot\Service\RobotApiService;
use Carbon\Carbon;
use Hyperf\Amqp\Producer;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Engine\Channel;
use Hyperf\Redis\Redis;
use Mine\Abstracts\AbstractService;
use Psr\Log\LoggerInterface;
use function Hyperf\Collection\collect;
use function Hyperf\Collection\data_get;
use function Hyperf\Coroutine\co;

class ActiveAddFriendService extends AbstractService
{
    public $mapper;
    protected Channel $channel;
    protected LoggerInterface $logger;
    protected Redis $redis;
    protected $type = OpSchemeTypeConstants::NEW_CUSTOMER;

    #[Inject]
    protected ChContactService $contactService;

    #[Inject]
    protected ActiveAddFriendConfigService $configService;

    #[Inject]
    protected ChRobotMapper $robotMapper;

    #[Inject]
    protected ActiveAddFriendRobotMapper $addFriendRobotMapper;

    #[Inject]
    protected ChContactMapper $contactMapper;

    #[Inject]
    protected ChOpSchemeRobotMapper $schemeRobotMapper;

    #[Inject]
    protected ChRoomMemberMapper $roomMemberMapper;

    #[Inject]
    protected ChRoomMapper $roomMapper;

    #[Inject]
    protected ActiveAddFriendRoomService $addRoomService;

    protected string $roomNameNumberPrefix = 'room_name_number:';

    public function __construct(ActiveAddFriendMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    public function updateFriendStatus($contact)
    {
        $this->mapper->updateByCondition([
            'main_uid'=>$contact->main_uid,
            'uid'=>$contact->uid,
            'add_robot_id'=>$contact->robot_id,
            'user_id'=>$contact->user_id,
        ],[
            'contact_id'=>$contact->id,
            'status'=>1,
            'wechat_status'=>2,
        ]);
    }

    public function autoRemark($contact,$isNew):bool
    {
        $config = $this->configService->getOperateConfig(['uid' => $contact->uid]);
        if(empty($config) || $config['is_auto_node'] == 0){
            return false;
        }
        //查询手机号
        $record=$this->mapper->first([
            'main_uid'=>$contact->main_uid,
            'uid'=>$contact->uid,
            'contact_id'=>$contact->id,
        ]);
        if(empty($record)){
            return false;
        }
        if($isNew || $config['is_update_node'] == 1){
            var_dump('主动加好友自动备注...');
            $this->handleAutoRemark($config, $contact, $record->mobile);
        }
        //打标签
        $this->addTags($contact,$record);
        return true;
    }


    /**
     * 主动加好友入口
     */
    public function addFriend($data)
    {
        $config = $this->configService->getConfig(['uid' => $data['uid'], 'main_uid' => $data['main_uid']]);
        // ===== 配置项 =====
        $isAutoStopByMuchMessage = (int)$this->configService->getConfigValue($config, 'is_auto_stop_by_much_message');
        $isAutoStopByLowPass = (int)$this->configService->getConfigValue($config, 'is_auto_stop_by_low_pass');
        $wechatDisableCfg = $this->configService->getConfigValue($config, 'wechat_disable_cfg');
        $isAddTagByMobileSearch = (int)$this->configService->getConfigValue($config, 'is_add_tag_by_mobile_search');
        $greetingInterval = $this->configService->getConfigValue($config, 'greeting_interval');
        //只处理待通过和未通过的
        if($data['wechat_status'] != 1 && $data['wechat_status'] != 0)
        {
            return;
        }
        $contact = $this->contactMapper->findByRobotIdAndUserId($data['add_robot_id'], $data['user_id']);
        if ($contact !== null) {
            $this->autoOperate($contact,false);
            return;
        }
        //处理长时间未通过的
        if($data['wechat_status']==1){
            $isReAdd = (int)$this->configService->getConfigValue($config, 'is_re_add');
            $reAddCfg = $this->configService->getConfigValue($config, 're_add_cfg');
            $addHour = isset($reAddCfg['add_hour']) ? (int)$reAddCfg['add_hour'] : 72;
            $addNumber = isset($reAddCfg['add_number']) ? (int)$reAddCfg['add_number'] : 2;
            if($isReAdd){
                if($data['add_number'] > $addNumber){
                    //超过添加次数
                    $this->mapper->update($data['id'],['status'=>2,'wechat_status'=>3]);
                    return;
                }
                //再次添加
                $add_time=Carbon::parse($data['add_time'])->timestamp + 3600*$addHour;
                if(time()>$add_time){
                    $delayInSeconds=rand($greetingInterval['min'],$greetingInterval['max']);
                    container()->get(LowQueueService::class)->push(new CommonJob(new CommonJobDto(
                        classname: ActiveAddFriendService::class,
                        method: 'addContacts',
                        data: [
                            'data' => $data,
                        ]
                    )), $delayInSeconds);
                }
                return;
            }
        }

        $delayInSeconds=rand($greetingInterval['min'],$greetingInterval['max']);
        var_dump('延迟添加好友时间。。。'.$delayInSeconds);
        container()->get(LowQueueService::class)->push(new CommonJob(new CommonJobDto(
            classname: ActiveAddFriendService::class,
            method: 'addContacts',
            data: [
                'data' => $data,
            ]
        )), $delayInSeconds);

    }

    public function addContacts(array $data)
    {
        $data=$data['data'];
        var_dump('队列中数据。。。');
        var_dump($data);
        //$config = $this->configService->getConfig(['uid' => $data['uid'], 'main_uid' => $data['main_uid']]);
        $robotInfo=$this->robotMapper->findById($data['add_robot_id']);
        $robotApiService=make(RobotApiService::class, [$robotInfo->server_id, $robotInfo->robot_key]);
        $content = '';
        //随机选择话术
        $record = ChAddFriendContent::inRandomOrder()
            ->where('main_uid', $data['main_uid'])
            ->where('uid', $data['uid'])
            ->where('group_id', $data['group_id'])
            ->where('status',1)
            ->first();
        if($record !== null){
            $content = $record['content'];
        }
        var_dump('发送内容。。。'.$content);
        $result=$robotApiService->addSearchContacts($data['union_id'],$data['user_id'],$content);
        var_dump($result);
        if($result===false){
            $this->mapper->update($data['id'],[
                'status'=>2,
                'wechat_status'=>3,
                'send_status'=>1,
                'add_number'=>Db::raw('add_number + 1'),
                'add_time'=>date('Y-m-d H:i:s',time())
            ]);
        }else{
            $this->mapper->update($data['id'],[
                'add_number'=>Db::raw('add_number + 1'),
                'send_status'=>1,
                'wechat_status'=>1,
                'add_time'=>date('Y-m-d H:i:s',time())
            ]);
        }
        Db::table('ch_add_friend_robot')->where('robot_id', $data['add_robot_id'])->update([
            'hello_time' => Db::raw('hello_time + 1')
        ]);
    }

    //添加频繁自动启用
    public function autoRecover($data)
    {
        $this->addFriendRobotMapper->disable($data['ids']);
        $config = $this->configService->getConfig($data);
        $isAutoAddRecover = (int)$this->configService->getConfigValue($config, 'is_auto_add_recover');
        $delayInSeconds = 24 * 60 * 60;
        if ($isAutoAddRecover === 1) {
            container()->get(LowQueueService::class)->push(new CommonJob(new CommonJobDto(
                classname: ActiveAddFriendRobotService::class,
                method: 'enable',
                data: [
                    'ids' => $data['ids'],
                ]
            )), $delayInSeconds);
            $this->addFriendRobotMapper->enable($data['ids']);
        }
    }

    //消息频繁自动停用
    public function AutoStopByMuchMessage($data)
    {
        $config = $this->configService->getConfig($data);
        $isAutoStopByMuchMessage = (int)$this->configService->getConfigValue($config, 'is_auto_stop_by_much_message');
        $delayInSeconds = 24 * 60 * 60;
        if ($isAutoStopByMuchMessage === 1) {
            $this->addFriendRobotMapper->disable($data['ids']);
            container()->get(LowQueueService::class)->push(new CommonJob(new CommonJobDto(
                classname: ActiveAddFriendRobotService::class,
                method: 'enable',
                data: [
                    'ids' => $data['ids'],
                ]
            )), $delayInSeconds);
            $this->addFriendRobotMapper->enable($data['ids']);
        }
    }

    public function addTask($data)
    {
        $addRobot = $data["addRobot"];
        $robotId = $addRobot["robot_id"];
        $record = $data["recordData"];
        $addNumber = $record['add_number'];
        $isReAdd = $data["isReAdd"];
        $addHour = $data["addHour"];
        $addNumberLimit = $data["addNumber"]+1;
        // === 1. 先执行正常加好友逻辑 ===
        $this->sendInvite($robotId, $record);

        // === 2. 处理 reAdd 逻辑 ===
        if ($isReAdd != 1) {
            return; // 如果未开启 reAdd，直接返回
        }

        // 查询最新的记录信息，防止数据过时
        $newRecord = Db::table('ch_add_friend')->where('id', $record['id'])->first()->toArray();

        // 如果 wechat_status == 2，则不再尝试
        if (!empty($newRecord['wechat_status']) && $newRecord['wechat_status'] == 2) {
            return;
        }

        // 判断 add_number 是否超过限制
        if (!empty($newRecord['add_number']) && $newRecord['add_number'] >= $addNumberLimit) {
            return;
        }

        // 计算下一次执行时间
        $nextAddTime = Carbon::now()->addHours($addHour)->toDateTimeString();

        // 更新数据库 next_add_time
        Db::table('ch_add_friend')
            ->where('id', $record['id'])
            ->update(['next_add_time' => $nextAddTime]);

        // 将任务推入队列
        container()->get(Producer::class)->produce(
            new ActiveAddFriendProducers(
                (new ActiveAddFriendProducersDto())
                    ->setMainUid($data['mainUid'])
                    ->setUid($data['uid'])
                    ->setGreetingInterval($data['greetInterval'])
                    ->setRobotData($addRobot)
                    ->setRecordData($newRecord)
                    ->setIsReAdd($isReAdd)
                    ->setAddHour($addHour)
                    ->setAddNumber($addNumber),
            )
        );
    }


    public function addTags($contact,$record)
    {
        if ($record) {
            $corpTagIds = array_column(json_decode($record->corp_tags ?? '[]', true), 'id');
            $smartTagIds = array_column(json_decode($record->smart_tags ?? '[]', true), 'id');

            $contactService = container()->get(ChContactService::class);
            $data = [
                'uid' => $contact->uid,
                'id' => $contact->id,
                'type' => 0,
            ];

            // 处理智能标签
            if (!empty($smartTagIds)) {
                $data['smart_tag_ids'] = json_encode($smartTagIds);
                $contactService->setSmartTag($data);
            }

            // 处理企业标签
            if (!empty($corpTagIds)) {
                $data['corp_tag_ids'] = json_encode($corpTagIds);
                $contactService->setCorpTag($data);
            }
        }
    }

    public function sendInvite(int $robotId,array $record)
    {
        if($record['status'] = 2 && $record['wechat_status'] = 2 && isset($record['wechat_status']))
        {
            return;
        }
        $uid = $record['uid'];
        $groupId   = $record['group_id'];
        $addRobot = $this->robotMapper->findById($robotId);

        $robotApiService = make(Robot::class, [$addRobot->server_id, $addRobot->uuid])->gateway();

        $result = $robotApiService->searchContact($record['mobile']);

        if($result !== false && $result['search_status'] ==1 && !empty($result['wx_user_info'])){
            $wxUserInfo = $result['wx_user_info'];
            $unionId = $wxUserInfo['union_id'];
            $userId = $wxUserInfo['user_id'];

            $contact = $this->contactMapper->findByRobotIdAndUserId($robotId, $userId);

            if ($contact !== null) {
                $this->autoOperate($record['uid'],false);
            }
            else{
                $content = '';
                //随机选择话术
                $record = ChAddFriendContent::inRandomOrder()
                    ->where('uid', $uid)
                    ->where('group_id', $groupId)
                    ->where('status',1)
                    ->first();
                if($record !== null){
                    $content = $record['content'];
                }
                $addResult = $robotApiService->addSearchWxContact($userId,$unionId,$content);

                if($addResult !== false){
                    Db::table('ch_add_friend')
                        ->where('id',$record['id'])
                        ->update(['user_id'=>$userId]);
                }
            }
        }

        //更新记录
        Db::transaction(function () use ($record, $robotId, $result,$content) {
            Db::table('ch_add_friend')->where('id', $record['id'])->update([
                'status' => 1,
                'wechat_status' => $result ? 1 : 0,
                'content' => $content??null,
                'add_number' => Db::raw('add_number + 1'),
                'add_time' => date('Y-m-d H:i:s', time()),
                'updated_at' => date('Y-m-d H:i:s', time()),
            ]);
            Db::table('ch_add_friend_robot')->where('robot_id', $robotId)->update([
                'hello_time' => Db::raw('hello_time + 1')
            ]);
        });
    }

    public function reset()
    {
        Db::table('ch_add_friend_robot')->update(['hello_time' => 0]);
        return true;
    }

    public function autoOperate($contact, bool $isNewFriend)
    {
        var_dump('已经是好友。。。');
       $this->autoRemark($contact,$isNewFriend);
       $this->sendContent($contact,$isNewFriend);
    }

    public function getInviteRoom($contact,$cfg)
    {
        $max_number=$cfg['draw_group_cfg']['max_number'];
        //更新群状态为已满
        $this->addRoomService->mapper->model::query()
            ->where('main_uid', $contact->main_uid)
            ->where('uid', $contact->uid)
            ->where('add_number', '>=',$max_number)
            ->update(['status' => 3]);
        //查询可用群
        $room=$this->addRoomService->mapper->model::query()
            ->where('main_uid', $contact->main_uid)
            ->where('uid', $contact->uid)
            ->where('robot_id', $contact->robot_id)
            ->where('status', 1)
            ->oldest()
            ->first();
        if(empty($room)){
            //先找替补中的
            $room=$this->addRoomService->mapper->model::query()
                ->where('main_uid', $contact->main_uid)
                ->where('uid', $contact->uid)
                ->where('robot_id', $contact->robot_id)
                ->where('status', 2)
                ->oldest()
                ->first();
            if($room){
                $room->status=1;
                $room->save();
            }
        }
        if(empty($room) || $room->add_number >=$cfg['draw_group_cfg']['max_number'] ){
            //新建群
            if(!$cfg['draw_group_cfg']['is_auto_create_room']){
                return false;
            }
            var_dump('自动建群');
            $robotInfo=$this->robotMapper->findById($contact->robot_id);
            $robotApiService = make(RobotApiService::class, [$robotInfo->server_id, $robotInfo->robot_key]);
            $result = $robotApiService->createRoom([$contact->user_id]);
            if($result === false){
                return false;
            }
            $room=$this->addRoomService->mapper->model::query()->updateOrCreate([
                'main_uid'=>$contact->main_uid,
                'room_wxid'=>$result['room_id'],
                'create_user_id'=>$contact->user_id,
                'robot_id'=>$contact->robot_id,
            ],[
                'add_number'=>0,
                'human_ceiling'=>$cfg['draw_group_cfg']['max_number'],
                'is_new'=>1,
                'status'=>1,
            ]);
            co(function () use($cfg,$robotApiService,$result,$contact){
                $createRule = $cfg['draw_group_cfg']['auto_create_room_cfg'];
                // 1. 获取群编号（原子操作）
                $key='add_friend_room_auto_name:'.$contact->uid.$contact->robot_id;
                $roomNameNumber = redis()->incr($key);
                if (empty($roomNameNumber)) { // 首次需要设置初始值
                    $initialNo = $createRule['no'] ?? 1;
                    $roomNameNumber = redis()->set($key, $initialNo) ? $initialNo : 1;
                }
                $roomName = $createRule['name'] ?? '默认群名称';
                $newRoomName = $roomName . $roomNameNumber;
                $robotApiService->editRoomName($result['room_id'], $newRoomName);
            });

        }
        $room->add_number=$room->add_number+1;
        $room->save();
        return $room;

    }

    /**
     * 处理新好友逻辑
     */
    private function sendContent( $contact,$isNewFriend=false): bool
    {
        $config = $this->configService->getOperateConfig(['uid' => $contact->uid]);
        if(empty($config) || $config['is_auto_operate'] == 0 || $isNewFriend){
            return false;
        }
        $cfg=$config['operate_cfg'];
        //查询手机号
        $record=$this->mapper->first([
            'main_uid'=>$contact->main_uid,
            'uid'=>$contact->uid,
            'contact_id'=>$contact->id,
        ]);
        if(empty($record)){
            return false;
        }
        $sendContent = data_get($cfg, 'quick_reply', []);
        $is_auto_draw_group = data_get($cfg, 'is_auto_draw_group', 0);

        if(empty($sendContent)){
            return false;
        }

        // 发送运营消息
        $sendContent=TagReplacer::changeData($sendContent,  [
            'call_name_nickname' => $contact->call_name ?: $contact->nickname,
            'gender' => $contact->gender,
            'add_time' => datetime($contact->add_customer_time, 'Y-m-d'),
        ]);
        var_dump('运营内容...');
        foreach ($sendContent as $key=>$content){
            if($content['msg_type']=='crowd'){
                $room=$this->getInviteRoom($contact,$cfg);
                if($room === false){
                    unset($sendContent[$key]);
                    break;
                }
                $sendContent[$key]['member_list']=[$contact->user_id];
                $sendContent[$key]['extra']['room_wxid']=$room->room_wxid;
                break;
            }
        }
        var_dump($sendContent);
        $recordData = [[
            'uid' => $contact->uid,
            'main_uid' => $contact->main_uid,
            'task_id' => $record->id,
            'robot_id' => $contact->robot_id,
            'to_id' => $contact->user_id,
            'trigger_time' => time(),
            'content' => $sendContent,
            'msg_total_count' => count($sendContent),
            'type' => SendConfigConstants::GREET_SOMEONE,
            'is_room' => 0,
        ]];

        container()->get(Producer::class)->produce(new SendRecordProducers(
            (new SendRecordProducersDto())
                ->setMainUid($contact->main_uid)
                ->setUid($contact->uid)
                ->setTaskId($recordData[0]['task_id'] ?? 0)
                ->setType(SendConfigConstants::GREET_SOMEONE)
                ->setRecordData($recordData)
                ->setIsSendNow(true)
        ));
        return true;
    }

    /**
     * 处理非新好友逻辑
     */
    private function handleExistingFriend($config, $contact, $mobile, $robotId)
    {
        $schemeId = 0;
        // 自动更新备注
        $this->handleAutoRemark($config, $contact, $mobile);

        // 自动回复
        if ($config->is_auto_operate == 1 && $config->operate_cfg['is_auto_draw_group'] == 1) {
            $operateCfg = $config->operate_cfg;
            $drawRoomCfg = data_get($operateCfg, 'draw_group_cfg', []);
            $sendContent = data_get($operateCfg, 'quick_reply', []);
            $autoCreateRoomCfg = $drawRoomCfg[0]['auto_create_room_cfg'] ?? null;
            $roomName = $autoCreateRoomCfg['name'] ?? '默认群名';
            $robot = $this->robotMapper->findById($robotId);

            // 获取当前群编号
            $redis = redis();
            $key = $this->roomNameNumberPrefix . $schemeId . ':' . RoomInviteLogTypeConstants::TYPE_GREETING;
            $roomNameNumber = (int)($redis->get($key) ?? ($autoCreateRoomCfg['no'] ?? 1));

            // 判断是否已有群
            $room = Db::table('ch_add_friend_room')
                ->where(['uid' => $contact->uid, 'status' => 1, 'create_user_id' => $robot->user_id])
                ->first();

            foreach ($sendContent as $item) {
                foreach ($item['content'] as $msg) {
                    $msgType = $msg['msg_type'] ?? 'text';
                    $content = $msg['content'] ?? '';
                    $extra = $msg['extra']['limit'] ?? ['unit' => 1, 'value' => 0];

                    // 延迟时间
                    $delayInSeconds = match ($extra['unit']) {
                        1 => $extra['value'],        // 秒
                        2 => $extra['value'] * 60,   // 分钟
                        3 => $extra['value'] * 3600, // 小时
                        default => 0,
                    };

                    // crowd 群操作
                    if ($msgType === 'crowd') {
                        if ($room) {
                            // 群存在，检查用户是否已在群
                            $isMember = $this->roomMemberMapper->checkRoomMemberExist($room->room_wxid, $contact->user_id, 0);
                            if (!$isMember) {
                                // 直接发邀请消息
                                container()->get(LowQueueService::class)->push(new CommonJob(new CommonJobDto(
                                    classname: RoomInviteService::class,
                                    method: 'sendRoomInvite',
                                    data: [
                                        'robot_id' => $robotId,
                                        'to_id' => $room->room_wxid,
                                        'msg_type' => 'crowd',
                                        'content' => ['member_list' => [$contact->user_id]],
                                        'scheme_id' => $schemeId,
                                        'type' => RoomInviteLogTypeConstants::TYPE_GREETING,
                                    ]
                                )), $delayInSeconds);

                                $this->addRoomService->updateAddNumber($room,$contact);
                            }
                        } else {
                            // 无群，新建群
                            $newRoomName = $roomName . $roomNameNumber;
                            $memberList = [$contact->user_id];

                            // 固定成员
                            $fixedMembers = $autoCreateRoomCfg['group_members'] ?? [];
                            foreach ($fixedMembers as $member) {
                                $memberList = array_merge($memberList, $member['user_ids'] ?? []);
                            }

                            // 企业成员
                            $employeeUserIds = $autoCreateRoomCfg['employee_user_ids'] ?? [];
                            $memberList = array_merge($memberList, $employeeUserIds);

                            // 创建群
                            container()->get(LowQueueService::class)->push(new CommonJob(new CommonJobDto(
                                classname: RoomInviteService::class,
                                method: 'createRoom',
                                data: [
                                    'robot_id' => $robotId,
                                    'user_id' => $contact->user_id,
                                    'fixed_members' => $memberList,
                                    'room_name' => $newRoomName,
                                    'key' => $this->roomNameNumberPrefix . $schemeId . ':' . RoomInviteLogTypeConstants::TYPE_GREETING,
                                    'scheme_id' => $schemeId,
                                    'type' => RoomInviteLogTypeConstants::TYPE_GREETING,
                                ]
                            )), $delayInSeconds);

                            // 群编号自增
                            $roomNameNumber = $redis->incr($key); // 原子操作
                        }
                    } else {
                        // 发送普通消息
                        container()->get(LowQueueService::class)->push(new CommonJob(new CommonJobDto(
                            classname: RoomInviteService::class,
                            method: 'sendRoomInvite',
                            data: [
                                'robot_id' => $robotId,
                                'to_id' => $contact->user_id,
                                'msg_type' => $msgType,
                                'content' => $content,
                                'scheme_id' => $schemeId,
                                'type' => RoomInviteLogTypeConstants::TYPE_GREETING,
                            ]
                        )), $delayInSeconds);
                    }
                }
            }
        }

        return true;
    }

    /**
     * 获取新客户运营机器人方案
     */
    private function getRobotScheme($robotId)
    {
        $robotSchemeList = $this->schemeRobotMapper->findRobotScheme($robotId, $this->type);
        if (empty($robotSchemeList)) return null;

        $robotScheme = $robotSchemeList->filter(fn($item) => !empty($item->scheme) && $item->scheme->is_default == 0)->first()
            ?: $robotSchemeList->filter(fn($item) => !empty($item->scheme) && $item->scheme->is_default == 1)->first();

        return $robotScheme;
    }

    /**
     * 处理自动备注
     */
    private function handleAutoRemark($config, $contact, $mobile, $cfg = null)
    {
        $autoRemarkContent = data_get($config['node_content'], 'auto_remark_content') ?: ($cfg ? data_get($cfg, 'auto_remark_content') : '');

        $autoRemarkContent = TagReplacer::replaceTags($autoRemarkContent, [
            'nickname' => $contact->nickname,
            'gender' => $contact->gender,
            'add_time' => datetime($contact->add_customer_time, 'Y-m-d'),
            'mobile' => $mobile,
        ]);
        $this->addContactTask($contact, $autoRemarkContent);
    }
    /**
     * 添加备注任务
     */
    private function addContactTask($contact, $content)
    {
        $taskData = new ContactTcContentDto();
        $taskData->setContactIds([$contact->id]);
        $taskData->setExtra([
            'type' => 0,
            'content' => $content,
        ]);
        container()->get(ChContactTaskCenterService::class)->addTask(
            $contact->uid,
            $contact->main_uid,
            ContactTaskCenterTyperConstants::EDIT_REMARK,
            $taskData
        );
    }

    public function processUniqueUidAndMainUid()
    {
        $this->mapper->model::query()->groupBy('uid', 'main_uid')->select(['uid', 'main_uid'])->chunk(100, function ($users) {
            foreach ($users as $user){
                //判断是否开启
                $config = $this->configService->getConfig(['uid' => $user->uid, 'main_uid' => $user->main_uid]);
                $isStartTask = (int)$this->configService->getConfigValue($config, 'is_start_task');
                if ($isStartTask != 1) {
                    continue;
                }
                //判断是佛在打招呼时间段
                $greeting_time=$this->configService->getConfigValue($config, 'greeting_time');
                $now=Carbon::now();
                $start = Carbon::parse($greeting_time['min']);
                $end = Carbon::parse($greeting_time['max']);
                if(!$now->between($start,$end)){
                    continue;
                }
                //获取待分配的机器人
                $addRobots = $this->addFriendRobotMapper->usedRobots($user->uid);
                if (empty($addRobots)) {
                    return true;
                }
                $addRobotGroups = collect($addRobots)->groupBy('group_id')->toArray();
                //创建协程运行
                co(function () use ($user,$addRobotGroups) {
                    $this->mapper->model::query()->where('main_uid',$user->main_uid)->where('uid',$user->uid)->whereIn('status',[0,3])->whereIn('wechat_status',[0,1])
                        ->chunk(100, function ($records)use($addRobotGroups) {
                            foreach ($records as $record) {
                                //1.处理待分配的机器人
                                if($record->status==0){
                                    $this->processAllocation($record,$addRobotGroups);
                                    continue;
                                }
                                //2.添加好友，并且发送打招呼信息
                                $this->addFriend($record->toArray());
                            }
                        });
                });
            }
        });

    }

    /**
     * 分配机器人
     */
    public function processAllocation($record,array $addRobotGroups):void
    {
        // 获取机器人并按 group_id 分组
        if(empty($addRobotGroups[$record->group_id])){
            return;
        }
        $addRobots = $addRobotGroups[$record->group_id];
        $useRobot=$addRobots[array_rand($addRobots)];
        $robotInfo=$this->robotMapper->findById($useRobot['robot']['id']);
        //搜索机器人
        $robotApiService = make(RobotApiService::class, [$robotInfo->server_id, $robotInfo->robot_key]);
        $times=0;
        $result=false;
        while ($times < 3){
            $resultTemp = $robotApiService->searchContacts($record->mobile);
            var_dump($resultTemp);
            if($resultTemp !== false){
                $result = $resultTemp;
                break;
            }
            $times++;
            sleep(1);
        }
        $data=[
            'add_robot_id' => $useRobot['robot_id'],
        ];
        if($result !== false && $result['search_status'] ==1 && !empty($result['wx_user_info'])){
            $wechat_status=0;
            $status=3;
            $wxUserInfo = $result['wx_user_info'];
            $data['union_id'] = $wxUserInfo['union_id'];
            $data['user_id'] = $wxUserInfo['user_id'];
        }else{
            //微信状态： 0=待处理 1=待通过 2=已通过 3=已失败  4-未搜到联系人
            $wechat_status=4;
            //打招呼状态：0=待分配 1=已完成 2=已失败  3=已分配
            $status=2;
        }
        $data['status']=$status;
        $data['wechat_status']=$wechat_status;
        $record->update($data);
    }
}